//
//  MasterViewController.swift
//  zh
//
//  Created by admin on 14/10/21.
//  Copyright (c) 2014年 sinosun. All rights reserved.
//

import UIKit


class MasterViewController: UITableViewController,NSURLSessionTaskDelegate,NSURLSessionDelegate {

    var session : NSURLSession?
    var detailViewController: DetailViewController? = nil
    var objects = NSMutableArray()
    
    
    required init(coder aDecoder: NSCoder) {
        //fatalError("init(coder:) has not been implemented")
        super.init(coder: aDecoder)
        var configration = NSURLSessionConfiguration.defaultSessionConfiguration()
        configration.timeoutIntervalForRequest = 3
        self.session = NSURLSession(configuration: configration, delegate: self, delegateQueue: nil)

    }



    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.clearsSelectionOnViewWillAppear = false
        self.preferredContentSize = CGSize(width: 320.0, height: 600.0)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        var url = NSURL(string: LATEST_NEWS)
        var request = NSURLRequest(URL: url, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 3)
        
        var task = session?.dataTaskWithRequest(request, completionHandler: nil)

        
        task?.resume()
        

        println("self.objects.count=\(self.objects.count)")
        
        let controllers = self.splitViewController!.viewControllers
        self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }



    // MARK: - Segues

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "showDetail" {
            if let indexPath = self.tableView.indexPathForSelectedRow() {
                let object = objects[indexPath.row] as NSDate
                let controller = (segue.destinationViewController as UINavigationController).topViewController as DetailViewController
                controller.detailItem = object
                controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
                controller.navigationItem.leftItemsSupplementBackButton = true
            }
        }
    }

    // MARK: - Table View

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return objects.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

        let object = objects[indexPath.row] as NSDictionary
        cell.textLabel?.text = object["title"] as? String
        return cell
    }

    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }

    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            objects.removeObjectAtIndex(indexPath.row)
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
        }
    }

    /* Sent as the last message related to a specific task.  Error may be
    * nil, which implies that no error occurred and this task is complete.
    */
    func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?){
        println("didCompleteWithError")
        println(error)
        if error == nil{
            println("dddd")
             println("self.objects.count=\(self.objects.count)")
            self.tableView.reloadData()
        }
    }
    
    func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?){
        session.finishTasksAndInvalidate()
    }
    
    
    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData){
        println(data)
        //解析网络请求数据
        var e : NSError?
        var jsonData: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &e)
        println("-------------")
        println(jsonData)
        if e == nil{
            println("数据请求完成，开始解析数据")
            if jsonData is NSDictionary{
                var date = jsonData!["date"] as String
                var storys = jsonData!["stories"] as NSArray
                println(date)
                for story in storys {

                    self.objects.addObject(story)
                }

                println("self.objects.count=\(self.objects.count)")
            }else{
                println("解析出错")
            }
        }
    }

}

